//
//  SCRNManager.m
//  Shuaiche
//
//  Created by xiangtao on 2024/2/20.
//  Copyright © 2024 ShuaiChe. All rights reserved.
//

#import "SCRNManager.h"
#import "SCCarImageUploadContainerVc.h"
#import "UserDefaultsUtils.h"
#import "SCBrandBoxVC.h"
#import "SCVinScanViewController.h"
#import "SCTestReportUploadVC.h"
#import "SCCarMaintenReportVC.h"
#import "SCMapViewController.h"
#import "Config.h"
#import "SDWebImageManager.h"
#import <Photos/Photos.h> // 用于保存到相册
#import "SCAppConfig.h"
#import "TZImagePickerController.h"
#import "SCCarAddImageModel.h"
#import "SCImageUploadManager.h"
#import "SCIMUploadManager.h"
#import "SCRNEventManager.h"


typedef void(^Result)(NSData *fileData, NSString *fileName);

@interface SCRNManager()<TZImagePickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@end

@implementation SCRNManager

RCT_EXPORT_MODULE(AndroidModule);

//清空vc
RCT_EXPORT_METHOD(clearCtr)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
        NSArray  *ctrls = @[[self getCurrentVC].navigationController.viewControllers[0],[self getCurrentVC].navigationController.viewControllers.lastObject];
        [self getCurrentVC].navigationController.viewControllers = ctrls;
    });
}

//清空前一级vc
RCT_EXPORT_METHOD(clearPreLevelCtr)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
        NSMutableArray *ctrls = [NSMutableArray arrayWithArray:[self getCurrentVC].navigationController.viewControllers];
        if (ctrls.count > 2) {
            [ctrls removeObjectAtIndex:ctrls.count-2];
            [self getCurrentVC].navigationController.viewControllers = ctrls;
        }
    });
}

//跳转到登录页面
RCT_EXPORT_METHOD(gotoLogin:(NSDictionary *)parameters)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    [[NSNotificationCenter defaultCenter] postNotificationName:SCNOTIFICATION_LOGIN object:nil];
  });
}

//session过期
RCT_EXPORT_METHOD(sessionExpired)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    [Config showLoginWhenSessionExpired];
  });
}

//退出登录
RCT_EXPORT_METHOD(logout)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    [Config userLogout];
  });
}

//退出登录成功
RCT_EXPORT_METHOD(logOffSuccess)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    [Config userLogout];
  });
}

//发车上传图片
RCT_EXPORT_METHOD(publishCarImageUpload:(NSDictionary *)params callback:(RCTResponseSenderBlock)callback)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
      NSString *index = [params objectForKey:@"index" defaultValue:nil];
      NSArray *carPics = [params objectForKey:@"carPics" matchClass:[NSArray class] defaultValue:nil];
      SCCarImageUploadContainerVc *uploadCtr = [[SCCarImageUploadContainerVc alloc] init];
      uploadCtr.imageUploadType = index.integerValue;
      uploadCtr.preShows = carPics;
      uploadCtr.completion = ^(NSArray *carPics){
        callback(@[[NSNull null],carPics]);
      };
      [[self getCurrentVC].navigationController pushViewController:uploadCtr animated:YES];
    });
}

//  选择品牌
RCT_EXPORT_METHOD(selectBrand:(NSDictionary *)parameters callback:(RCTResponseSenderBlock)callback)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    [self showBrandSelector:parameters result:^(NSDictionary *result){
      callback(@[[NSNull null],result]);
    }];
  });
}


//  选择车架号
RCT_EXPORT_METHOD(selectCarVin:(NSDictionary *)parameters callback:(RCTResponseSenderBlock)callback)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    SCVinScanViewController *scan = [[SCVinScanViewController alloc] init];
    [[self getCurrentVC].navigationController pushViewController:scan animated:YES];
    __weak typeof (self) weakSelf = self;
    scan.resultBlock = ^(NSString * vin) {
        callback(@[[NSNull null],vin]);
      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[weakSelf getCurrentVC].navigationController popViewControllerAnimated:YES];
      });
    };
  });
}

//选择检测报告
RCT_EXPORT_METHOD(selectCarDetection:(NSDictionary *)parameters callback:(RCTResponseSenderBlock)callback)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    SCTestReportUploadVC *vc = [[SCTestReportUploadVC alloc] init];
    vc.uploadType = SCReportUploadCarDetection;
    NSMutableDictionary *detectionParam = [NSMutableDictionary dictionaryWithCapacity:0];
    detectionParam[@"reportPcUrl"] = parameters[@"detectionReportUrl"];
    detectionParam[@"reportPic"] = parameters[@"detectionReportPic"];
    detectionParam[@"reportPdf"] = parameters[@"detectionReportPdf"];
    vc.upload = ^(NSDictionary * _Nonnull info) {
      NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
      params[@"detectionReportPic"] = info[@"reportPic"];
      params[@"detectionReportUrl"] = info[@"reportPcUrl"];
      params[@"detectionReportPdf"] = info[@"reportPdf"];
      callback(@[[NSNull null],params]);
    };
    vc.preParams = detectionParam;
    [[self getCurrentVC].navigationController pushViewController:vc animated:YES];
  });
}

//选择维保
RCT_EXPORT_METHOD(uploadMaintenanceReport:(NSDictionary *)parameters callback:(RCTResponseSenderBlock)callback)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    NSMutableDictionary *maintenParam = [NSMutableDictionary dictionaryWithCapacity:0];
    NSString *carId = parameters[@"carId"];
    NSString *page = parameters[@"page"];
    maintenParam[@"reportPcUrl"] = parameters[@"reportPcUrl"];
    maintenParam[@"reportPic"] = parameters[@"reportPic"];
    maintenParam[@"reportPdf"] = parameters[@"reportPdf"];
    SCCarMaintenReportVC *vc = [[SCCarMaintenReportVC alloc] init];
    vc.vcode = parameters[kVcode];
    vc.page = page;
    if (carId) {
      vc.carId = carId;
    }
    vc.upload = ^(NSDictionary * _Nonnull info) {
      NSLog(@"info = %@",info);
      NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
      params[@"reportPic"] = info[@"reportPic"];
      params[@"reportPcUrl"] = info[@"reportPcUrl"];
      params[@"reportPdf"] = info[@"reportPdf"];
      params[@"vcode"] = info[@"vcode"];
      callback(@[[NSNull null],params]);
    };
    vc.preParam = maintenParam;
    [[self getCurrentVC].navigationController pushViewController:vc animated:YES];
  });
}

//选择合同
RCT_EXPORT_METHOD(selectContract:(NSDictionary *)parameters callback:(RCTResponseSenderBlock)callback)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    SCTestReportUploadVC *vc = [[SCTestReportUploadVC alloc] init];
    vc.uploadType = SCReportUploadCarContract;
    NSMutableDictionary *detectionParam = [NSMutableDictionary dictionaryWithCapacity:0];
    detectionParam[@"reportPic"] = parameters[@"contractPic"];
    detectionParam[@"reportPdf"] = parameters[@"contractPdf"];
    vc.upload = ^(NSDictionary * _Nonnull info) {
      NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
      params[@"contractPic"] = info[@"reportPic"];
      params[@"contractPdf"] = info[@"reportPdf"];
      callback(@[[NSNull null],params]);
    };
    vc.preParams = detectionParam;
    [[self getCurrentVC].navigationController pushViewController:vc animated:YES];
  });
}

//  选择地图
RCT_EXPORT_METHOD(selectMap:(NSDictionary *)parameters callback:(RCTResponseSenderBlock)callback)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    SCMapViewController *map = [[SCMapViewController alloc] init];
    map.lat = parameters[@"lat"];
    map.lon = parameters[@"lon"];
    [[self getCurrentVC].navigationController pushViewController:map animated:YES];
    map.didSelectAddress = ^(NSDictionary * dic) {
      NSLog(@"dic = %@",dic);
      callback(@[[NSNull null],dic]);
      [[self getCurrentVC].navigationController popViewControllerAnimated:YES];
    };
  });
}

//更新userInfo
RCT_EXPORT_METHOD(updateUserInfo:(NSDictionary *)parameters)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    NSString *face = [parameters objectForKey:@"face" defaultValue:nil];
    NSString *fullname = [parameters objectForKey:@"fullname" defaultValue:nil];
    if (face) {
      [Config sharedConfig].user.face = face;
    }
    if (fullname) {
      [Config sharedConfig].user.fullname = fullname;
    }
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
  });
}

//切换环境
RCT_EXPORT_METHOD(switchApi:(NSDictionary *)parameters)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    NSString *switchType = [parameters objectForKey:@"switchType" defaultValue:nil];
    
    if (switchType.intValue == 1) {
      [[SCAppConfig sharedInstance] changeDomainWithEnv:@"dev"];
    } else if (switchType.intValue == 2) {
      [[SCAppConfig sharedInstance] changeDomainWithEnv:@"test"];
    } else if (switchType.intValue == 3) {
     [[SCAppConfig sharedInstance] changeDomainWithEnv:@"pro"];
    }
  });
}

//下载图片
RCT_EXPORT_METHOD(downloadPictures:(NSDictionary *)parameters)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    NSArray *imgList = [parameters objectForKey:@"imgList" matchClass:[NSArray class] defaultValue:nil];
    if (imgList) {
      [imgList enumerateObjectsUsingBlock:^(NSString *imageURL, NSUInteger idx, BOOL *stop){
        [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:imageURL]
                                                       options:SDWebImageHighPriority
                                                      progress:nil
                                                     completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                if (error) {
                  [MBProgressHUD showError:[NSString stringWithFormat:@"下载图片失败: %@",error.localizedDescription] toView:nil];
                    return;
                }
                if (image) {
                    // 下载成功，保存到相册
                    [self saveImageToPhotoAlbum:image];
                }
            }];
      }];
    }
  });
}

- (void)saveImageToPhotoAlbum:(UIImage *)image {
  // 请求相册权限
      [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
          if (status == PHAuthorizationStatusAuthorized) {
              // 有权限，保存图片
              [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                  [PHAssetChangeRequest creationRequestForAssetFromImage:image];
              } completionHandler:^(BOOL success, NSError * _Nullable error) {
                  dispatch_async(dispatch_get_main_queue(), ^{
                      if (success) {
                        [MBProgressHUD showSuccess:@"保存成功!" toView:nil];
                      } else {
                        [MBProgressHUD showError:[NSString stringWithFormat:@"图片保存失败: %@",error.localizedDescription] toView:nil];
                      }
                  });
              }];
          } else {
              dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"暂无相册权限,保存失败" toView:nil];
              });
          }
      }];
}


#pragma mark - brandSelector
- (void)showBrandSelector:(NSDictionary *)parameters result:(void(^)(NSDictionary *result))whenSelectResult {
  NSString *selectLevel = [parameters objectForKey:@"selectLevel" defaultValue:nil];
  SCBrandBoxVC *brandBoxVC = [[SCBrandBoxVC alloc] init];
  brandBoxVC.casecadeType = SCCasecadeTypeBrand;
  if (selectLevel.intValue == 2) {
    brandBoxVC.indexTitleType = SCSectionIndexTitleNotLimited;
  }
  brandBoxVC.selectedType = SCCarBrandSelectedTypeSearch;
  brandBoxVC.completion = ^(int brand, int series,int species,NSString *brandName,NSString *seriesName,NSString *speciesName) {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:0];
    if (brand) {
      parameters[@"brandId"] = @(brand);
    }
    if (brandName) {
      parameters[@"brandName"] = brandName;
    }
    if (series) {
      parameters[@"seriesId"] = @(series);
    }
    if (seriesName) {
      parameters[@"seriesName"] = seriesName;
    }
    if (species) {
      parameters[@"speciesId"] = @(species);
    }
    if (speciesName) {
      parameters[@"speciesName"] = speciesName;
    }
    
    NSMutableString *brandFullName = [NSMutableString stringWithCapacity:0];
    if (brandName) {
      [brandFullName appendString:brandName];
    }
    if (seriesName) {
      [brandFullName appendFormat:@" %@",seriesName];
    }
    if (speciesName) {
      [brandFullName appendFormat:@" %@",speciesName];
    }
    if (brandFullName.length > 0) {
      parameters[@"brandFullName"] = brandFullName;
    }
      whenSelectResult(parameters);
      [[self getCurrentVC].navigationController popViewControllerAnimated:YES];
  };
  brandBoxVC.parentId = 0;
  [[self getCurrentVC].navigationController pushViewController:brandBoxVC animated:YES];
}

- (void)pickPhotoFromAlbumAndUpload:(NSUInteger)imageNumber{

    TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:imageNumber delegate:self];
    // 设置是否可以选择视频/原图
    imagePickerController.allowPickingVideo = YES;
    imagePickerController.naviBgColor = [UIColor whiteColor];
    imagePickerController.naviTitleColor = [UIColor blackColor];
    imagePickerController.statusBarStyle = UIStatusBarStyleDefault;
    imagePickerController.barItemTextColor = [UIColor blackColor];
    imagePickerController.allowPickingOriginalPhoto = YES;
    imagePickerController.allowTakePicture = NO;
    imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
    
    imagePickerController.navLeftBarButtonSettingBlock = ^(UIButton *lefyButton){
        [lefyButton setImage:[UIImage imageNamed:@"back_icon"] forState:UIControlStateNormal];
    };
    [[self getCurrentVC] presentViewController:imagePickerController animated:YES completion:nil];
}


#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    if (photos.count <= 0) {
        [CoolAlertView showAlertWithTitle:@"请选择图片" message:nil];
        return;
    }
    
    NSMutableArray *imgArray = [NSMutableArray arrayWithCapacity:0];
    for (NSInteger index = 0; index < assets.count; index++) {
        SCCarAddImageItemModel *model = [[SCCarAddImageItemModel alloc] init];
        model.isAddButton = NO;
        model.asset = assets[index];
        model.image = photos[index];
        [imgArray addObject:model];
    }
    
    [self startEditImageOperationWithImages:imgArray];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset {
    [self getVideoFromPHAsset:asset Complete:^(NSData *fileData, NSString *fileName){
        dispatch_async(dispatch_get_main_queue(), ^(){
            NSLog(@"fileData = %ld, fileName = %@",fileData.length,fileName);
            if (uploadType == UploadTypeIMImageOrVideo) {
                [MBProgressHUD showMessage:@"视频上传中" toView:[self getCurrentVC].view];
                [SCIMUploadManager startUploadVideo:fileData completion:^(NSString *videoUrl, NSString *errorString){
                    NSLog(@"videoUrl = %@",videoUrl);
                    NSThread *thread = [NSThread currentThread];
                    dispatch_async(dispatch_get_main_queue(), ^(){
                        if (videoUrl) {
                            [MBProgressHUD hideHUDForView:[self getCurrentVC].view animated:YES];
                            NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:0];
                            parameters[@"fileOssPath"] = videoUrl;
                            parameters[@"fileName"] = fileName;
                            [[SCRNEventManager shareInstance] uploadIMSuccess:parameters];
                        } else {
                            [MBProgressHUD showError:@"图片上传失败"];
                        }
                    });
                }];
            }

        });
    }];
}

- (void)getVideoFromPHAsset:(PHAsset *)asset Complete:(Result)result {
    NSArray *assetResources = [PHAssetResource assetResourcesForAsset:asset];
    PHAssetResource *resource;

    for (PHAssetResource *assetRes in assetResources) {
        if (assetRes.type == PHAssetResourceTypePairedVideo ||
            assetRes.type == PHAssetResourceTypeVideo) {
            resource = assetRes;
        }
    }
    NSString *fileName = @"tempAssetVideo.mov";
    if (resource.originalFilename) {
        fileName = resource.originalFilename;
    }
    
    if (asset.mediaType == PHAssetMediaTypeVideo || asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive) {
        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
        options.version = PHImageRequestOptionsVersionCurrent;
        options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        
        NSString *PATH_MOVIE_FILE = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
        [[NSFileManager defaultManager] removeItemAtPath:PATH_MOVIE_FILE error:nil];
        [[PHAssetResourceManager defaultManager] writeDataForAssetResource:resource toFile:[NSURL fileURLWithPath:PATH_MOVIE_FILE] options:nil completionHandler:^(NSError * _Nullable error){
            if (error) {
                result(nil, nil);
            } else {
                NSData *data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:PATH_MOVIE_FILE]];
                result(data, fileName);
            }
            [[NSFileManager defaultManager] removeItemAtPath:PATH_MOVIE_FILE  error:nil];
        }];
    } else {
        result(nil, nil);
    }
}

- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker
{
    [[SCRNEventManager shareInstance] uploadCancel];
}

#pragma mark - startEditImageOperationWithImage
- (void)startEditImageOperationWithImages:(NSArray<SCCarAddImageItemModel *> *)imageArray
{
    [MBProgressHUD showMessage:@"图片上传中" toView:[self getCurrentVC].view];
    if (uploadType == UploadTypeImage) {
        [SCImageUploadManager startUploadImages:imageArray completion:^(NSArray * _Nonnull picUrls,NSString *errorString) {
            dispatch_async(dispatch_get_main_queue(), ^(){
                if (picUrls) {
                    [MBProgressHUD hideHUDForView:[self getCurrentVC].view animated:YES];
                    NSMutableArray *picUrlArray = [NSMutableArray arrayWithCapacity:0];
                    for (int i = 0; i < picUrls.count; i++) {
                        NSString *picUrl = picUrls[i];
                        NSString *picUrlStr = sc_url_img(picUrl);
                        [picUrlArray addObject:picUrlStr];
                    }
                    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:0];
                    parameters[@"picUrls"] = picUrlArray;
                    [[SCRNEventManager shareInstance] uploadSuccess:parameters];
                    
                } else {
                    [MBProgressHUD showError:@"图片上传失败"];
                }
            });
        }];
    } else if (uploadType == UploadTypeIMImageOrVideo) {
        SCCarAddImageItemModel *model = imageArray[0];
        [SCIMUploadManager startUploadImage:model.image completion:^(NSString * _Nonnull picUrl, NSString *fileName, NSString *errorString) {
            dispatch_async(dispatch_get_main_queue(), ^(){
                if (picUrl && fileName) {
                    [MBProgressHUD hideHUDForView:[self getCurrentVC].view animated:YES];
                    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:0];
                    parameters[@"fileOssPath"] = picUrl;
                    parameters[@"fileName"] = fileName;
                    [[SCRNEventManager shareInstance] uploadIMSuccess:parameters];
                } else {
                    [MBProgressHUD showError:@"图片上传失败"];
                }
            });
        }];
    }
    
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    UIImage *image= [info objectForKey:UIImagePickerControllerOriginalImage];
    [[self getCurrentVC] dismissViewControllerAnimated:YES completion:^{
        SCCarAddImageItemModel *model = [[SCCarAddImageItemModel alloc] init];
        model.isAddButton = NO;
        model.image = image;
        [self startEditImageOperationWithImages:@[model]];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [[self getCurrentVC] dismissViewControllerAnimated:YES completion:nil];
    [[SCRNEventManager shareInstance] uploadCancel];
}

#pragma mark - saveImage
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo
{
    NSString *message = @"保存失败";
    if (!error) {
        message = @"成功保存到相册";
        [MBProgressHUD showSuccess:message];
    }else
    {
        message = [error description];
        [MBProgressHUD showError:message];
    }
}


@end
